var DEFAULT_LAYER = 'catastro_regiones';
var DEFAULT_SRS = 'EPSG:4326';
var init = function() {
 
    
    //meter esta inicialización en una funcion
    var format = new OpenLayers.Format.WMTSCapabilities({
        /**
         * This particular service is not in compliance with the WMTS spec and
         * is providing coordinates in y, x order regardless of the CRS.  To
         * work around this, we can provide the format a table of CRS URN that
         * should be considered y, x order.  These will extend the defaults on
         * the format.
         */
        yx: {
            "urn:ogc:def:crs:EPSG:6.3:4326": true
        }
    });
    
    OpenLayers.Request.GET({
        url: "/map.fcgi/wmts/1.0.0/WMTSCapabilities.xml",
        
        success: function(request) {
            var doc = request.responseXML;
            if (!doc || !doc.documentElement) {
                doc = request.responseText;
            }
            var capabilities = format.read(doc);

            $.ajax({
                url: '/viewLayer/getSRSResolutions/'+encodeURIComponent(DEFAULT_SRS),
                type: 'GET',
                dataType: 'json',
                 
                success: function(data){
                    var resolutions = $.map(data.resolutions, function (res) {
                        return parseFloat(res);
                    });
                    // boundingBox de la capa
                    var srsExtentArray = data.extent;
                    
                    var srsExtent = new OpenLayers.Bounds(srsExtentArray['minX'],srsExtentArray['minY'],srsExtentArray['maxX'], srsExtentArray['maxY']);
                                    
                    var navhis= new OpenLayers.Control.NavigationHistory();
                    var scale = new OpenLayers.Control.Scale({
                        geodesic: true
                    });
                    var layerSwitcher = new OpenLayers.Control.LayerSwitcher('layerSwitcher',{
                        'ascending': false
                     
                    });
                    
                    // Creo el mapa
                    var map = new OpenLayers.Map( 'map', {
                        maxExtent: srsExtent,
                        projection: new OpenLayers.Projection(DEFAULT_SRS),
                
               
                        controls: [
                        new OpenLayers.Control.Navigation(),
                        new OpenLayers.Control.Attribution(),
                        new OpenLayers.Control.PanZoomBar(),
             
                        navhis,
                
                        new OpenLayers.Control.ScaleLine({
                            geodesic: true
                        }),
        
                        new OpenLayers.Control.MousePosition({
                            prefix: '<a target="_blank" ' +
                            'href="http://spatialreference.org/ref/epsg/4326/">' +
                            'EPSG:4326</a> coordinates: ',
                            formatOutput: function(lonLat) {
                                var markup = convertDMS(lonLat.lat, "LAT");
                                markup += " " + convertDMS(lonLat.lon, "LON");
                                return markup
           
                            }
                        }
                        ),
                
                        scale,
                
                        new OpenLayers.Control.KeyboardDefaults()
                        ],
                        allOverlays: true
        
                    } );
            
                    var panel = new OpenLayers.Control.Panel({
                        div: document.getElementById("panel")
                    });
            
                    panel.addControls([ navhis.previous,navhis.next ]);
                    map.addControl(panel);
            
                    map.addControl(layerSwitcher);
                    var wmts_layer = new OpenLayers.Layer.WMTS({
                        name:  'catastro_regiones',
                        url: "/map.fcgi/wmts/",
                        layer:  'catastro_regiones',
                        matrixSet: DEFAULT_SRS,
                        requestEncoding: 'REST',
                        visibility: true,
                        format: 'image/png',
                        style: 'default',
                        gutter:0,
                        buffer:0,
                        isBaseLayer:false,
                        transitionEffect:'resize',
                        resolutions:resolutions,
                        zoomOffset:0,
                        maxExtent: srsExtent,
                        projection: new OpenLayers.Projection(DEFAULT_SRS),
                        sphericalMercator: false
                    });
                    map.addLayer(wmts_layer);
                    setMapCenter(map);
                                    
                    //cargo las capas
                    $.each (capabilities.contents.layers , function(index,layer) {
                        //si la capa tiene el srs
                        if(layer.title != DEFAULT_LAYER  && layerHasSRS(layer,DEFAULT_SRS)) {
                            $.ajax({
                                url: '/basicViewer/getLayerData/'+layer.title,
                                type: 'GET',
       
                                dataType: 'json',
                                success: function(data){
                                    // obtengo el bbox y las resoluciones  srs (debe machear cuando defino la capa)
                                    var srsAttr = data.grids[DEFAULT_SRS]['@attributes'];
                                    //var layerBbox =  srsAttr && srsAttr['restricted_extent'] ? srsAttr['restricted_extent'] : null ;
                                    //var layerBboxArray = layerBbox ? layerBbox.split(' ') : null;
                                    //var layerExtent = layerBboxArray ? new  OpenLayers.Bounds(layerBboxArray[0],layerBboxArray[1],layerBboxArray[2], layerBboxArray[3]) : srsExtent;
                                    var minZoom = srsAttr && srsAttr['minZoom'] ? srsAttr['minZoom'] : 0 ;
                                    var maxZoom = srsAttr && srsAttr['maxZoom'] ? srsAttr['maxZoom'] : resolutions.length ;
                                    var limitedResolutions = resolutions.slice(minZoom, maxZoom);
                                    
                                    var wmts_layer = new OpenLayers.Layer.WMTS({
                                        name:  layer.title,
                                        url: "/map.fcgi/wmts/",
                                        layer:  layer.title,
                                        matrixSet: DEFAULT_SRS,
                                        requestEncoding: 'REST',
                                        visibility: false,
                                        format: 'image/png',
                                        style: 'default',
                                        gutter:0,
                                        buffer:0,
                                        isBaseLayer:false,
                                        transitionEffect:'resize',
                                        resolutions:limitedResolutions,
                                        zoomOffset:0,
                                        maxExtent:  srsExtent,
                                        projection: new OpenLayers.Projection(DEFAULT_SRS),
                                        sphericalMercator: false
                                    });
                                    map.addLayer(wmts_layer);
                                    setMapCenter(map);

                                }
                            });

                        }
                    });
                    
                    map.events.register("zoomend", map, function(e){
                        updateScale(e);
                    });
  
                }
            }
            );
           
        }
    });
}

function updateScale(e) {
    $('#currentScale').val(e.object.getScale());
    $('#currentZoomLevel').val(e.object.getZoom());
}
function layerHasSRS(layer,srs) {
    return ($.grep(layer.tileMatrixSetLinks,function(e){
        return e.tileMatrixSet == srs;
    })).length > 0;
}
function setMapCenter(map) {
    if(!map.getCenter()){
        map.zoomToMaxExtent();
        map.setCenter(new OpenLayers.LonLat(-60,-31));
    }               
    $('#currentScale').val(map.getScale());
    $('#currentZoomLevel').val(map.getZoom());
}
window.addEventListener("DOMContentLoaded", init )